package Offer2017;

/**
 * 二叉搜索树转换为双向链表
 * Created by 雷文康 on 2018/1/1.
 */
public class Test27 {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(10);
        TreeNode node2 = new TreeNode(5);
        TreeNode node3 = new TreeNode(12);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(7);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node3.right = null;
        node4.left = node4.right = null;
        node5.left = node5.right = null;
        TreeNode p = min(node1);
        while (p != null) {
            System.out.print(p.value);
            System.out.print(" ");
            p = p.right;
        }
    }

    public static TreeNode min(TreeNode root) {
        if (root == null) {
            return null;
        }
        root.left = max(root.left);
        if (root.left != null) {
            root.left.right = root;
        }

        root.right = min(root.right);
        if (root.right != null) {
            root.right.left = root;
        }
        while (root.left != null) {
            root = root.left;
        }
        return root;
    }

    public static TreeNode max(TreeNode root) {
        if (root == null) {
            return null;
        }
        root.left = max(root.left);
        if (root.left != null) {
            root.left.right = root;
        }

        root.right = min(root.right);
        if (root.right != null) {
            root.right.left = root;
        }
        while (root.right != null) {
            root = root.right;
        }
        return root;
    }
}
